package com.hcss.common.redis.base.impl;

import com.hcss.common.redis.base.RedisMapDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @描述: Map类型RedisTemplate Dao层实现
 * @作者: xuqian
 * @创建日期: 2018-01-15 13:53
 * @公司 浙江鸿程计算机系统有限公司
 */
@Repository("redisMapDao")
public class RedisMapDaoImpl<K, T> implements RedisMapDao<K, T> {

    private final HashOperations hashOperations;

    private final RedisTemplate redisTemplate;

    @Autowired
    public RedisMapDaoImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.hashOperations = redisTemplate.opsForHash();
    }

    @Override
    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    @Override
    public HashOperations getHashOperations() {
        return hashOperations;
    }

    @Override
    public void clear(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void clearAll(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    @Override
    public void put(String key, K mkey, T mvalue) {
        hashOperations.put(key, mkey, mvalue);
    }

    @Override
    public void putAll(String key, Map<K, T> map) {
        hashOperations.putAll(key, map);
    }

    @Override
    public T get(String key, K mkey) {
        return (T)hashOperations.get(key, mkey);
    }

    @Override
    public List<T> get(String key, K[] mkeys) {
        List<K> hashKeys = Arrays.asList(mkeys);
        return hashOperations.multiGet(key, hashKeys);
    }

    @Override
    public Map<K, T> getAll(String key) {
        return hashOperations.entries(key);
    }

    @Override
    public void delete(String key, K[] mkeys) {
        hashOperations.delete(key, mkeys);
    }

    @Override
    public boolean contantsKey(String key, K mkey) {
        return hashOperations.hasKey(key, mkey);
    }

    @Override
    public Set<K> getKeys(String key) {
        return hashOperations.keys(key);
    }

    @Override
    public List<T> getValues(String key) {
        return hashOperations.values(key);
    }

    @Override
    public Long size(String key) {
        return hashOperations.size(key);
    }

    @Override
    public void setTime(String key, long time, TimeUnit unit) {
        redisTemplate.expire(key, time, unit);
    }

	@Override
	public Set<String> fuzzyKeys(String fuzzyKey) {
		return redisTemplate.keys(fuzzyKey);
	}

}
